package com.chenfan.ccp.plug.business.service;

import com.chenfan.ccp.plug.business.enums.BusinessLogTypeEnums;
import com.chenfan.ccp.entity.CollectEventListener;
import com.chenfan.ccp.plug.business.entity.BusinessLog;
import com.google.common.eventbus.Subscribe;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class BusinessCollectService {

    private static final Map<String, BusinessLog> collectCache = new ConcurrentHashMap<>();

    public static void put(String traceId, String data, BusinessLogTypeEnums typeEnums) {
        if (traceId == null || traceId.isEmpty() || data == null || data.isEmpty()) {
            return;
        }
        BusinessLog businessLog = collectCache.getOrDefault(traceId, new BusinessLog());
        switch (typeEnums) {
            case RPC:
//                if (businessLog.getRpcData() != null) {
//                    businessLog.setRpcData(data + "\n" + businessLog.getRpcData());
//                } else {
//                    businessLog.setRpcData(data);
//                }
                break;
            case MYSQL:
//                if (businessLog.getMysqlData() != null) {
//                    businessLog.setMysqlData(data + "\n" + businessLog.getMysqlData());
//                } else {
//                    businessLog.setMysqlData(data);
//                }
                break;
            case REDIS:

//                if (businessLog.getRedisData() != null) {
//                    businessLog.setRedisData(data + "\n" + businessLog.getRedisData());
//                } else {
//                    businessLog.setRedisData(data);
//                }

                break;
            case HTTP:
//
//                if (businessLog.getHttpData() != null) {
//                    businessLog.setHttpData(data + "\n" + businessLog.getHttpData());
//                } else {
//                    businessLog.setHttpData(data);
//                }

                break;

        }

        collectCache.put(traceId, businessLog);


    }

    public static void remove(String traceId) {
        if (traceId == null || traceId.isEmpty()) {
            return;
        }
        collectCache.remove(traceId);
    }

    public static BusinessLog getBusinessLog(String traceId) {
        if (traceId == null || traceId.isEmpty()) {
            return new BusinessLog();
        }
        return collectCache.getOrDefault(traceId, new BusinessLog());
    }

    @Subscribe
    public void collect(CollectEventListener eventListener) {
        put(eventListener.getTraceId(), eventListener.getData(), eventListener.getType());
    }
}
